<?php
declare (strict_types = 1);

namespace app\applet\controller;
use think\facade\Db;
use think\facade\Config;
class Index
{
    /**
     *静默操作 仅保存 openid
     * 进入页面直接将获取openid，并且将他存入wx_uesr表中，返回id进行其他操作
     **/
    public function setOpenid(){
        $data = request()->param();
        //接收code
        $code = $data['code'];
        $openid_data = json_decode($this->getUserOpenid($code),true);
        $openid = $openid_data['openid'];
        $wx_user = Db::table("wx_user")->where("openid",$openid)->find();
        //查询是否存储该用户
        if(!empty($wx_user)){
            return json(['status'=>200,"msg"=>"用户存在,返回数据成功",'id'=>$wx_user['wx_id']]);
        }else{
            $id = Db::table("wx_user")->insertGetId(['openid'=>$openid]);
            return json(['status'=>200,"msg"=>"用户身份已创建，返回数据成功",'id'=>$id]);
        }
    }
    /**
     *静默操作 保存用户信息
     * 进入页面直接将获取openid，并且将他存入wx_uesr表中，返回id进行其他操作
     * 用法：前端uni.getUserProfile将uni.login套在里头，发起请求
     **/
    public function setUserInfo(){
        $data = request()->param();
        //接收code
        $code = $data['code'];
        $openid_url = 'https://api.weixin.qq.com/sns/jscode2session?appid='.config('wx')['appletAppId'].'&secret='.config('wx')['appletAppSecret'].'&js_code='.$code.'&grant_type=authorization_code';
        $openid_data = json_decode(req_Get($openid_url),true);
        $openid = $openid_data['openid'];
        $wxs_user = Db::table("wxs_user")->where("wxs_openid",$openid)->find();
        /**
        DROP TABLE IF EXISTS `wxs_user`;

        CREATE TABLE `wxs_user` (
        `wxs_id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'id',
        `wxs_openid` varchar(50) DEFAULT NULL COMMENT '小程序获取微信openid',
        `wxs_nickName` varchar(255) DEFAULT NULL COMMENT '小程序获取微信昵称',
        `wxs_avatarUrl` text COMMENT '小程序获取微信头像',
        `wxs_create_time` datetime DEFAULT NULL COMMENT '创建时间',
        PRIMARY KEY (`wxs_id`),
        KEY `wxs_id` (`wxs_id`)
        ) ENGINE=MyISAM DEFAULT CHARSET=utf8mb4;
         */
        //查询是否存储该用户
        if(!empty($wxs_user)){
            return json(['status'=>200,"msg"=>"用户存在,返回数据成功",'id'=>$wxs_user['wxs_id']]);
        }else{
            $result = [
                'wxs_openid'=>$openid,
                'wxs_nickName'=>$data['nickName'],
                'wxs_avatarUrl'=>$data['avatarUrl'],
                'wxs_create_time'=>date("Y-m-d H:i:s")
            ];

            $id = Db::table("wxs_user")->insertGetId($result);
            return json(['status'=>200,"msg"=>"用户身份已创建，返回数据成功",'id'=>$id]);
        }
    }
    /**
     * 发送订阅消息，此操作需要用户同意才可以接收到
     * $template_id 模板id
     * $openId 发送给哪个用户，取出openid
     * 其他自定义
    */
    public function sendApi($template_id,$openId,$sign_time,$sign_day,$sign_name,$sign_num,$msg){
        //先获取ACCESS_TOKEN
        $get_access_token_url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.config('wx')['appletAppId'].'&secret='.config('wx')['appletAppSecret'];
        //请求得到全部access等全部信息
        $access_token_arr = json_decode(req_Get($get_access_token_url),true);
        $access_token = $access_token_arr['access_token'];
        $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;
        //模板id 编号3436
        $udata['template_id'] = $template_id;
        $udata['touser'] = $openId;
        //发送的消息模板
        $udata['data'] = array(
            'date7'=>['value'=>$sign_time],//参观日期
            'character_string6'=>['value'=>$sign_day],//入馆时段
            'name1'=>['value'=>$sign_name],//姓名
            'number8'=>['value'=>$sign_num],//参观人数
            'thing9'=>['value'=>$msg]//"您的预约登记成功"
        );
        //跳转小程序类型developer为开发版；trial为体验版；formal为正式版；默认为正式版
        $udata['miniprogram_state'] = "trial";
        $udata['lang'] = "zh_CN";
        //var_dump(json_encode($udata));
        return req_Post($url,json_encode($udata));

    }

}
